﻿using LogSystem;
using NodeCanvas.Framework;
using ParadoxNotion.Design;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI.Utils;

namespace Yoozoo.Gameplay.Liberty.AI.Node
{
    [Category("Ggame/Liberty")]
    public class NpcSShapeMove : AIBaseNode
    {
        public BBParameter<TargetType> targetType = TargetType.CurrentLockTarget;
        public BBParameter<float> offset = 2;
        public BBParameter<float> errorRange = 0.6f;
        public BBParameter<float> errorTime = 2f;
        // public BBParameter<bool> isVerticle = false;

        private int flag = 1;   // 正负方向
        private Vector3 recordDestinationPostion = Vector3.zero;

        protected override void OnExecute()
        {
            AIEntity target = _entity.battleAgent.GetTarget(targetType.value);

            // 切换方向
            if (flag == 1)
            {
                flag = -1;
            }
            else
            {
                flag = 1;
            }
            
            // 根据目标向量，计算位置
            Vector3 currentPos = _entity.battleAgent.transform.position;
            Vector3 targetPos = target.battleAgent.transform.position;
            Vector3 targetVector = targetPos - currentPos;
            bool isVerticle = false;
            switch (_entity.data.npcAIModel)
            {
                case NpcAIModel.HorzontalSShapeMoveAttack:
                    isVerticle = false;
                    break;
                case NpcAIModel.VerticleSShapeMoveAttack:
                    isVerticle = true;
                    break;
                case NpcAIModel.RandomSShapeMoveAttack:
                    isVerticle = Random.Range(0, 100) >= 50;
                    break;
            }
            
            if (isVerticle)
            {
                // 前后移动
                Vector3 forward = targetVector.normalized;
                recordDestinationPostion = currentPos + forward * offset.value * flag;
            }
            else
            {
                // 左右移动
                Vector3 right = Vector3.Cross(Vector3.up, targetVector).normalized;
                recordDestinationPostion = currentPos + right * offset.value * flag;
            }
            SetDestination(recordDestinationPostion);
        }
        
        protected override void OnUpdate()
        {
            base.SetTransformData();
            float dis = Vector3.Distance(recordDestinationPostion, _entity.battleAgent.transform.position);
            if (_entity.seeker.ReachedEndOfPath() || dis < errorRange.value || elapsedTime>=errorTime.value)
            {
                EndAction(true);
            }
        }
        
    }
}